package member

import (
	"time"
	"dhfshop/models/member"
	"dhfshop/controllers/base"
	"github.com/astaxie/beego/validation"
)

type AccountConfController struct {
	base.BaseController
}

// 开启状态查询
func (this *AccountConfController) StatusGet() {
	partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	open := member.CheckAccountConfExist(partnerId)
	rsp := struct {
		Open   bool   `json:"open"`
	}{Open: open}
	this.Data["json"] = rsp
	this.ServeJSON()
}

// 开启
func (this *AccountConfController) Post() {
	partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	if err := member.InitDefaultAccountConf(partnerId); err != nil {
	    this.ServeError(err.Error())
	    return
	}
	rsp := struct {
		PartnerId int64        `json:"partner_id"`
	    Modified  time.Time `json:"modified"`
	}{PartnerId: partnerId, Modified:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

// 关闭
func (this *AccountConfController) Delete() {
	partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	if err := member.DeleteAccountConf(partnerId); err != nil {
	    this.ServeError(err.Error())
	    return
	}
    r := struct {
		PartnerId int64       `json:"partner_id"`
	    Modified  time.Time `json:"modified"`
	}{PartnerId:partnerId, Modified:time.Now().UTC()}
	this.Data["json"] = r 
	this.ServeJSON()
}

// 参数查询
func (this *AccountConfController) Get() {
	//curRoleId := this.Ctx.Input.GetData("curRoleId").(int) 
	companyId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	if curUserId == 0 {
		this.ServeError("user is not login")
	    return
	}
	conf, err := member.GetAccountConfById(companyId)
	if err != nil {
	    this.ServeError(err.Error())
		return
	}
	this.Data["json"] = conf
	this.ServeJSON()
}

// 参数更新
func (this *AccountConfController) Put() {
    v := member.AccountConf{}
	this.ParseForm(&v)
	v.PartnerId = int64(this.Ctx.Input.GetData("curCompanyId").(int))
	valid := validation.Validation{}
	valid.Required(v.PartnerId, "partner_id")
	passed, _ := valid.Valid(&v)
	if !passed {
	    this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
	excludeArr := []string{"partner_id"}
	updateFields, err := this.GetUpdateFields(v, "", "form", excludeArr)
	if err != nil {
	    this.ServeError(err.Error())
		return
	}
	if err = member.UpdateAccountConfById(&v, updateFields...); err != nil{
		this.ServeError(err.Error())
		return
	}
	rsp := struct {
		Id       int64         `json:"partner_id"`
	    Modified time.Time   `json:"modified"`
	}{Id:v.PartnerId, Modified:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}	

